//
//  FeaturedViewController.m
//  KeYin
//
//  Created by Sean Chen on 5/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FeaturedViewController.h"


@implementation FeaturedViewController

@synthesize magazine;
@synthesize periodicals;
@synthesize loadingPageIndex;
@synthesize selectedPeriodicalIndex;
@synthesize processViewController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (id)initWithMagazine:(NSDictionary *)dict {
    self = [super init];
    if (self) {
        self.magazine = dict;
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.periodicals = [NSMutableArray array];
    
    if (magazine) {
        self.navigationItem.title = [magazine objectForKey:@"name"];
    } else {
        self.navigationItem.title = @"新刊推荐";
    }
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(refresh)];
    self.navigationItem.rightBarButtonItem = item;
    [item release];
    
    pageIdx = 1;
    pageSize = 4;
    hasMore = YES;
    
    [self loadWithPolicy:TTURLRequestCachePolicyDefault];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload
{
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc
{
    [magazine release];
    [periodicals release];
    [processViewController release];
    
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {    
    [super viewWillDisappear:animated];
    [self.tableView reloadData];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
}

#pragma mark - IBAction

- (IBAction)read:(id)sender {
    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
    //detailViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (hasMore) {
        return periodicals.count + 1;
    } else {
        return periodicals.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= periodicals.count) {
        return 44;
    } else {
        return 128;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *periodicalCellIdentifier = @"PeriodicalCell";
    static NSString *moreCellIdentifier = @"MoreCell";
    
    if (indexPath.row >= periodicals.count) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:moreCellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:moreCellIdentifier];
        }
        
        cell.textLabel.text = @"读取更多";
        cell.textLabel.textColor = [UIColor lightGrayColor];
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
        return cell;
    }
    
    PeriodicalCell *cell = (PeriodicalCell *)[tableView dequeueReusableCellWithIdentifier:periodicalCellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"PeriodicalCell" owner:self options:nil];
        cell = periodicalCell;
        self.periodicalCell = nil;
    }
    
    // Configure the cell
    NSDictionary *dict = [periodicals objectAtIndex:indexPath.row];
    
    cell.thumb.urlPath = [dict objectForKey:@"cover_img"];
    cell.title.text = [dict objectForKey:@"name"];
    cell.date.text = [dict objectForKey:@"date"];
    cell.description.text = [dict objectForKey:@"description"];
    
    if ([M13FileManager exits:dict inFile:kFileNamePeriodicals]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row >= periodicals.count) {
        //pageIdx += pageSize;
        pageIdx += 1;
        [self loadWithPolicy:TTURLRequestCachePolicyDefault];
        return;
    }
    
    self.selectedPeriodicalIndex = indexPath.row;
    
    NSDictionary *periodical = [periodicals objectAtIndex:indexPath.row];
    
    if ([M13FileManager exits:periodical inFile:kFileNamePeriodicals]) {
        [self readSelectedPeriodical];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"确认要下载？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"下载", nil];
        [alert setTag:1];
        [alert show];
        [alert release];
    }
}

#pragma mark - TTURLRequestDelegate

- (void)requestDidFinishLoad:(TTURLRequest*)request {
    TTURLJSONResponse *response = request.response;
    
    NSDictionary *rootDict = response.rootObject;
    NSDictionary *result = [rootDict objectForKey:@"result"];
    //NSLog(@"result = %@", result);
    NSArray *entries;
    if (magazine) {
        entries = [result objectForKey:@"periodicals"];
    } else {
        entries = [result objectForKey:@"new_magazines"];
    }
    
    //self.periodicals = entries;
    [periodicals addObjectsFromArray:entries];
    
    if (entries.count < pageSize) {
        hasMore = NO;
    }
    
    [self.tableView reloadData];
    
    //NSLog(@"featuredPericals = %@", featuredPericals);
}

- (void)request:(TTURLRequest*)request didFailLoadWithError:(NSError*)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"联网失败 请稍后再试" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

#pragma mark - private

- (void)refresh {
    hasMore = YES;
    pageIdx = 1;
    [periodicals removeAllObjects];
    [self loadWithPolicy:TTURLRequestCachePolicyNetwork];
}

- (void)loadWithPolicy:(TTURLRequestCachePolicy)policy {
    NSString *URL;
    if (magazine) {
        //URL = [NSString stringWithFormat:@"http://www.keyin.cn/ipad/get_magazines_list.php?magazine_id=%@&page_index=1&page_size=20", [magazine objectForKey:@"magazine_id"]];
        
        URL = [NSString stringWithFormat:@"http://www.keyin.cn/ipad/get_magazines_list.php?magazine_id=%@&page_index=%d&page_size=%d", [magazine objectForKey:@"magazine_id"], pageIdx, pageSize];
    } else {
        URL = @"http://www.keyin.cn/ipad/new_magazines.php";
        hasMore = NO;
    }
    TTURLRequest *request = [TTURLRequest requestWithURL:URL delegate:self];
    
    TTURLJSONResponse *response = [[TTURLJSONResponse alloc] init];
    request.response = response;
    [response release];
    
    request.cachePolicy = policy;
    
    [request send];
}

- (void)downloadSelectedPeriodical {
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSDictionary *periodical = [periodicals objectAtIndex:selectedPeriodicalIndex];
    NSString *src;
    NSString *ID = [periodical objectForKey:@"periodical_id"];
    NSString *pageName;
    NSUInteger pages = [[periodical objectForKey:@"pages"] integerValue];
    
    loadingPageIndex = 0;
    BOOL success = YES;
    
    while (loadingPageIndex < pages) {
        
        src = [NSString stringWithFormat:@"http://www.keyin.cn/ipad/get_magazine.php?periodical_id=%@&page=%d", ID, loadingPageIndex + 1];
        //NSLog(@"src = %@", src);
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:src]];
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        if (!data) {
            success = NO;
            break;
        }
        pageName = [NSString stringWithFormat:kFileNamePage, ID, loadingPageIndex];
        [data writeToFile:[M13FileManager filePathWithFileName:pageName] atomically:YES];
        
        
        
        src = [NSString stringWithFormat:@"%@_s",src];
        request = [NSURLRequest requestWithURL:[NSURL URLWithString:src]];
        data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        if (!data) {
            success = NO;
            break;
        }
        pageName = [NSString stringWithFormat:kFileNameThumb, ID, loadingPageIndex];
        [data writeToFile:[M13FileManager filePathWithFileName:pageName] atomically:YES];
        
        
        
        loadingPageIndex++;
        
        [self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:(CGFloat)loadingPageIndex/pages] waitUntilDone:NO];
    }
    
    if (success) {
        [M13FileManager add:periodical toFile:kFileNamePeriodicals];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"下载失败 请稍后再试" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];
        [alert release];
        
        [processViewController.view removeFromSuperview];
    }
    
    [pool release];
}

- (void)readSelectedPeriodical {
    NSDictionary *periodical = [periodicals objectAtIndex:selectedPeriodicalIndex];
    
    ContentViewController *detailViewController = [[ContentViewController alloc] initWithPeriodical:periodical];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

- (void)updateProgress:(NSNumber *)progress {
    
    [processViewController updateProgress:[progress floatValue]];
    
    if ([progress integerValue] == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"下载完成 立即阅读？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"阅读", nil];
        [alert setTag:2];
        [alert show];
        [alert release];
        
        [self.tableView reloadData];
    }
}

#pragma mark -
#pragma UIAlertViewDelegate

//DownloadingConfirmAlert Tag = 1,
//ReadingConfirmAlert Tag = 2
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if ([alertView tag] == 1 && buttonIndex == 1) {
        
        self.processViewController = [[ProcessViewController alloc] initWithNibName:@"ProcessViewController" bundle:nil];
        processViewController.view.frame = CGRectMake(0.0, 20.0, 320.0, 460.0);
        [[[UIApplication sharedApplication].windows objectAtIndex:0] addSubview:processViewController.view];
        
        [self performSelectorInBackground:@selector(downloadSelectedPeriodical) withObject:nil];
        
    } else if ([alertView tag] == 2) {
        
        if (buttonIndex == 1) {
            [self readSelectedPeriodical];
        }
        
        [processViewController.view removeFromSuperview];
    }
}

@end
